package com.vise.bledemo.jky;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.vise.baseble.ViseBle;
import com.vise.baseble.callback.scan.IScanCallback;
import com.vise.baseble.callback.scan.ScanCallback;
import com.vise.baseble.model.BluetoothLeDevice;
import com.vise.baseble.model.BluetoothLeDeviceStore;
import com.vise.bledemo.R;
import com.vise.bledemo.activity.DeviceDetailActivity;
import com.vise.bledemo.adapter.DeviceAdapter;
import com.vise.bledemo.view.CompanyCustomView2;
import com.vise.log.ViseLog;
import com.xys.libzxing.zxing.activity.CaptureActivity;

import java.util.ArrayList;
import java.util.List;

public class JKYDeviceScanActivity extends AppCompatActivity {

    private static final int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 100;

    private ListView deviceLv;
    private TextView scanCountTv;
    private CompanyCustomView2 cv2;
    //设备扫描结果展示适配器
    private DeviceAdapter adapter;
    private List<BluetoothLeDevice> methodResult = new ArrayList<>();
    private BluetoothLeDeviceStore bluetoothLeDeviceStore = new BluetoothLeDeviceStore();
    private BluetoothLeDevice mDevice;
    /**
     * 扫描回调
     */
    private ScanCallback periodScanCallback = new ScanCallback(new IScanCallback() {
        @SuppressLint("MissingPermission")
        @Override
        public void onDeviceFound(final BluetoothLeDevice bluetoothLeDevice) {
            ViseLog.i("Founded Scan Device:" + bluetoothLeDevice);
            Log.e("", "" + bluetoothLeDevice.getDevice().getName());
            if (!TextUtils.isEmpty(bluetoothLeDevice.getDevice().getName())) {
//            if (!TextUtils.isEmpty(bluetoothLeDevice.getDevice().getName()) && bluetoothLeDevice.getDevice().getName().contains("NBeeNET")) {
                bluetoothLeDeviceStore.addDevice(bluetoothLeDevice);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (adapter != null && bluetoothLeDeviceStore != null) {
                            methodResult.clear();
                            methodResult.addAll(bluetoothLeDeviceStore.getDeviceList());
                            adapter.setListAll(bluetoothLeDeviceStore.getDeviceList());
                            updateItemCount(adapter.getCount());
                        }
                    }
                });
            }
        }

        @Override
        public void onScanFinish(BluetoothLeDeviceStore bluetoothLeDeviceStore) {
            ViseLog.i("scan finish " + bluetoothLeDeviceStore);
        }

        @Override
        public void onScanTimeout() {
            ViseLog.i("scan timeout");
        }

    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jkydevice_scan);
        ToastUtils.init(getApplication());
        init();
        cv2.setSearchCall(new CompanyCustomView2.SearchCall() {
            @Override
            public void searchCallString(String key) {
                if (isScanIng) {
                    ToastUtils.show("请扫描完毕后使用");
                    return;
                }
                if (TextUtils.isEmpty(key)) {
                    adapter.setListAll(methodResult);
                    updateItemCount(methodResult.size());
                } else {
                    List<BluetoothLeDevice> temp = new ArrayList<>();
                    for (BluetoothLeDevice bluetoothLeDevice : methodResult) {
                        String deviceName = bluetoothLeDevice.getDevice().getName();
                        if (deviceName.contains(key)) {
                            temp.add(bluetoothLeDevice);
                        }
                    }
                    adapter.setListAll(temp);
                    updateItemCount(temp.size());
                }
            }
        });
        updateItemCount(0);
        XXPermissions.with(this)
                // 申请单个权限
                .permission(Permission.ACCESS_FINE_LOCATION)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .permission(Permission.CAMERA)
                // 申请多个权限
                .permission(Permission.Group.BLUETOOTH)
                // 设置权限请求拦截器（局部设置）
                //.interceptor(new PermissionInterceptor())
                // 设置不触发错误检测机制（局部设置）
                //.unchecked()
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (!all) {
                            ToastUtils.show("获取蓝牙 位置部分权限成功，但部分权限未正常授予");
                            return;
                        }
                        ToastUtils.show("获取蓝牙 位置权限成功");

                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            ToastUtils.show("蓝牙 位置被永久拒绝授权，请手动授予录音和日历权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(JKYDeviceScanActivity.this, permissions);
                        } else {
                            ToastUtils.show("获取蓝牙 位置权限失败");
                        }
                    }
                });


        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent openCameraIntent = new Intent(JKYDeviceScanActivity.this, CaptureActivity.class);
                startActivityForResult(openCameraIntent, 0);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString("result");
            ToastUtils.show(scanResult);
            BTQRTestActivity.startLHYtest(JKYDeviceScanActivity.this, scanResult);
        }
    }


    private void init() {
        cv2 = (CompanyCustomView2) findViewById(R.id.cv2);
        deviceLv = (ListView) findViewById(android.R.id.list);
        scanCountTv = (TextView) findViewById(R.id.scan_device_count);

        adapter = new DeviceAdapter(this);
        deviceLv.setAdapter(adapter);

        deviceLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                //点击某个扫描到的设备进入设备详细信息界面
                BluetoothLeDevice device = (BluetoothLeDevice) adapter.getItem(position);
                if (device == null) {
                    return;
                }
//                Intent intent = new Intent(JKYDeviceScanActivity.this, DeviceDetailActivity.class);
                Intent intent = new Intent(JKYDeviceScanActivity.this, BLEDeviceConnectActivity.class);
                intent.putExtra(DeviceDetailActivity.EXTRA_DEVICE, device);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
//        startScan();
        invalidateOptionsMenu();
    }

    @Override
    protected void onPause() {
        super.onPause();
//        stopScan();
        invalidateOptionsMenu();
        bluetoothLeDeviceStore.clear();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 菜单栏的显示
     *
     * @param menu 菜单
     * @return 返回是否拦截操作
     */
    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        getMenuInflater().inflate(R.menu.scan, menu);
        if (periodScanCallback != null && !periodScanCallback.isScanning()) {
            menu.findItem(R.id.menu_stop).setVisible(false);
            menu.findItem(R.id.menu_scan).setVisible(true);
            menu.findItem(R.id.menu_refresh).setActionView(null);
        } else {
            menu.findItem(R.id.menu_stop).setVisible(true);
            menu.findItem(R.id.menu_scan).setVisible(false);
            menu.findItem(R.id.menu_refresh).setActionView(R.layout.actionbar_progress_indeterminate);
        }
        return true;
    }

    /**
     * 点击菜单栏的处理
     *
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(final MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_scan://开始扫描
                startScan();
                break;
            case R.id.menu_stop://停止扫描
                stopScan();
                break;
        }
        return true;
    }

    boolean isScanIng = false;

    /**
     * 开始扫描
     */
    private void startScan() {
        isScanIng = true;
        cv2.cc2_edit1.setText("");
        updateItemCount(0);
        if (adapter != null) {
            adapter.setListAll(new ArrayList<BluetoothLeDevice>());
        }
        ViseBle.getInstance().startScan(periodScanCallback);
        invalidateOptionsMenu();
    }

    /**
     * 停止扫描
     */
    private void stopScan() {
        isScanIng = false;
        ViseBle.getInstance().stopScan(periodScanCallback);
        invalidateOptionsMenu();
    }

    /**
     * 更新扫描到的设备个数
     *
     * @param count
     */
    private void updateItemCount(final int count) {
        scanCountTv.setText(getString(R.string.formatter_item_count, String.valueOf(count)));
    }

}